public class UsePreAndInCreateTree {

    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public int preIndex;


    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return buildTreeChild(preorder,inorder,0,inorder.length - 1);
    }

    public TreeNode buildTreeChild(int[] preorder,int[] inorder,
                                   int inBegin,int inEnd){
        if(inBegin > inEnd){
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);
        int rootIndex = findVal(inorder,inBegin,inEnd,preorder[preIndex]);
        preIndex++;
        root.left = buildTreeChild(preorder,inorder,inBegin,rootIndex - 1);
        root.right = buildTreeChild(preorder,inorder,rootIndex + 1,inEnd);

        return root;

    }

    public int findVal(int[] inorder,int inBegin,
                       int inEnd,int val){
        for (int i = inBegin; i <= inEnd ; i++) {
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }
}
